<template>
  <div class="container">
    <page-header 
      title="车辆年检记录" 
      subtitle="记录和管理所有车辆的年检信息"
    >
      <template #actions>
        <el-button type="primary" @click="openAddDialog" class="btn-with-icon">
          <el-icon class="mr-1"><Plus /></el-icon>添加年检记录
        </el-button>
        <el-button type="success" @click="exportData" class="btn-with-icon">
          <el-icon class="mr-1"><Download /></el-icon>导出数据
        </el-button>
      </template>
    </page-header>
    
    <el-card shadow="hover" class="mb-6 card-with-hover">
      <div class="search-container flex items-center flex-wrap gap-4">
        <el-input
          v-model="searchQuery"
          placeholder="搜索车牌号/年检机构"
          prefix-icon="Search"
          clearable
          @clear="loadInspectionRecords"
          @input="debounceSearch"
          style="width: 240px"
          class="search-input"
        />
        <div class="flex gap-2 ml-auto">
          <el-button type="primary" @click="loadInspectionRecords" :loading="loading" class="search-btn">
            <el-icon class="mr-1"><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetSearch" class="reset-btn">
            <el-icon class="mr-1"><Refresh /></el-icon>重置
          </el-button>
        </div>
      </div>
    </el-card>
    
    <el-card shadow="hover" class="overflow-hidden card-with-hover">
      <el-table
        v-loading="loading"
        :data="inspectionRecords"
        border
        stripe
        style="width: 100%"
        :header-cell-class-name="'bg-gray-100 dark:bg-gray-700'"
        class="custom-table"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="vehicleNo" label="车牌号" width="120" />
        <el-table-column prop="inspectionDate" label="年检日期" width="120" />
        <el-table-column prop="expiryDate" label="有效期至" width="120" />
        <el-table-column prop="inspectionResult" label="年检结果" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getResultType(scope.row.inspectionResult)" effect="light" class="status-tag">
              {{ scope.row.inspectionResult }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="inspectionAgency" label="检测机构" width="150" />
        <el-table-column prop="cost" label="费用(元)" width="100" align="center" />
        <el-table-column prop="notes" label="备注" min-width="180" show-overflow-tooltip />
        <el-table-column prop="nextInspectionDate" label="下次年检日期" width="120" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <div class="flex gap-1">
              <el-button 
                type="primary" 
                size="small"
                @click="handleEdit(scope.row)"
                class="edit-btn"
              >
                <el-icon class="mr-1"><Edit /></el-icon>编辑
              </el-button>
              <el-button 
                type="danger" 
                size="small"
                @click="handleDelete(scope.row)"
                class="delete-btn"
              >
                <el-icon class="mr-1"><Delete /></el-icon>删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container mt-4 flex justify-center">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="DEFAULT_PAGE_SIZES"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          class="custom-pagination"
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑年检记录' : '添加年检记录'"
      width="600px"
      destroy-on-close
      class="custom-dialog"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        label-position="right"
        class="form-container"
      >
        <el-form-item label="车牌号" prop="vehicleNo">
          <el-select v-model="form.vehicleNo" placeholder="请选择车辆" filterable style="width: 100%">
            <el-option
              v-for="vehicle in vehicles"
              :key="vehicle.id"
              :label="vehicle.vehicleNo"
              :value="vehicle.vehicleNo"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="年检日期" prop="inspectionDate">
          <el-date-picker 
            v-model="form.inspectionDate" 
            type="date" 
            placeholder="选择年检日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="有效期至" prop="expiryDate">
          <el-date-picker 
            v-model="form.expiryDate" 
            type="date" 
            placeholder="选择有效期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="年检结果" prop="inspectionResult">
          <el-select v-model="form.inspectionResult" placeholder="请选择年检结果" style="width: 100%">
            <el-option label="通过" value="通过" />
            <el-option label="不通过" value="不通过" />
            <el-option label="限期整改" value="限期整改" />
          </el-select>
        </el-form-item>
        <el-form-item label="检测机构" prop="inspectionAgency">
          <el-input v-model="form.inspectionAgency" placeholder="请输入检测机构名称" />
        </el-form-item>
        <el-form-item label="费用" prop="cost">
          <el-input-number 
            v-model="form.cost" 
            :min="0" 
            :step="50"
            :precision="2"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input 
            v-model="form.notes" 
            type="textarea" 
            placeholder="请输入备注信息"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="下次年检日期" prop="nextInspectionDate">
          <el-date-picker 
            v-model="form.nextInspectionDate" 
            type="date" 
            placeholder="选择下次年检日期"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Download, Search, Edit, Delete, Refresh } from '@element-plus/icons-vue'
import PageHeader from '@/components/PageHeader.vue'
import { DEFAULT_PAGE_SIZES } from '@/utils/constants'
import axios from 'axios'

export default {
  name: 'InspectionView',
  components: {
    PageHeader,
    Plus,
    Download,
    Search,
    Edit,
    Delete,
    Refresh
  },
  setup() {
    const searchQuery = ref('')
    const inspectionRecords = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const dialogVisible = ref(false)
    const isEdit = ref(false)
    const formRef = ref(null)
    const vehicles = ref([])
    const submitLoading = ref(false)
    const loading = ref(false)
    
    // 表单数据
    const form = reactive({
      id: null,
      vehicleNo: '',
      inspectionDate: '',
      expiryDate: '',
      inspectionResult: '通过',
      inspectionAgency: '',
      cost: 0,
      notes: '',
      nextInspectionDate: ''
    })
    
    // 表单验证规则
    const rules = {
      vehicleNo: [{ required: true, message: '请选择车牌号', trigger: 'change' }],
      inspectionDate: [{ required: true, message: '请选择年检日期', trigger: 'change' }],
      expiryDate: [{ required: true, message: '请选择有效期', trigger: 'change' }],
      inspectionResult: [{ required: true, message: '请选择年检结果', trigger: 'change' }],
      inspectionAgency: [{ required: true, message: '请输入检测机构', trigger: 'blur' }],
      cost: [
        { required: true, message: '请输入年检费用', trigger: 'blur' },
        { type: 'number', message: '费用必须为数字', trigger: 'blur' }
      ]
    }
    
    // 初始化加载数据
    onMounted(() => {
      loadInspectionRecords()
      loadVehicles()
    })
    
    // 加载车辆列表
    const loadVehicles = async () => {
      try {
        const response = await axios.get('/api/vehicles')
        vehicles.value = response
      } catch (error) {
        ElMessage.error('获取车辆列表失败')
        console.error('获取车辆列表失败:', error)
      }
    }
    
    // 加载年检记录
    const loadInspectionRecords = async () => {
      loading.value = true
      try {
        const params = {
          page: currentPage.value,
          size: pageSize.value,
          query: searchQuery.value
        }
        const response = await axios.get('/api/maintenance/inspection', { params })
        inspectionRecords.value = response.list
        total.value = response.total
      } catch (error) {
        ElMessage.error('获取年检记录失败')
        console.error('获取年检记录失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 防抖搜索
    let searchTimeout = null
    const debounceSearch = () => {
      if (searchTimeout) {
        clearTimeout(searchTimeout)
      }
      searchTimeout = setTimeout(() => {
        loadInspectionRecords()
      }, 500)
    }
    
    // 重置搜索
    const resetSearch = () => {
      searchQuery.value = ''
      loadInspectionRecords()
    }
    
    // 处理分页大小变化
    const handleSizeChange = (val) => {
      pageSize.value = val
      loadInspectionRecords()
    }
    
    // 处理页码变化
    const handleCurrentChange = (val) => {
      currentPage.value = val
      loadInspectionRecords()
    }
    
    // 打开添加对话框
    const openAddDialog = () => {
      isEdit.value = false
      resetForm()
      dialogVisible.value = true
      
      // 等待DOM更新后重置表单验证
      setTimeout(() => {
        formRef.value && formRef.value.clearValidate()
      }, 0)
    }
    
    // 处理编辑
    const handleEdit = (row) => {
      isEdit.value = true
      resetForm()
      Object.keys(form).forEach(key => {
        if (key in row) {
          form[key] = row[key]
        }
      })
      dialogVisible.value = true
      
      // 等待DOM更新后重置表单验证
      setTimeout(() => {
        formRef.value && formRef.value.clearValidate()
      }, 0)
    }
    
    // 重置表单
    const resetForm = () => {
      Object.keys(form).forEach(key => {
        if (key === 'cost') {
          form[key] = 0
        } else if (key === 'inspectionDate' || key === 'expiryDate' || key === 'nextInspectionDate') {
          form[key] = ''
        } else if (key === 'inspectionResult') {
          form[key] = '通过'
        } else {
          form[key] = ''
        }
      })
    }
    
    // 处理删除
    const handleDelete = (row) => {
      ElMessageBox.confirm(
        `确定要删除车牌号为 ${row.vehicleNo} 的年检记录吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          await axios.delete(`/api/maintenance/inspection/${row.id}`)
          ElMessage.success('删除成功')
          loadInspectionRecords()
        } catch (error) {
          ElMessage.error('删除失败')
          console.error('删除失败:', error)
        }
      }).catch(() => {
        // 用户取消删除
      })
    }
    
    // 提交表单
    const submitForm = async () => {
      if (!formRef.value) return
      
      await formRef.value.validate(async (valid, fields) => {
        if (valid) {
          submitLoading.value = true
          try {
            if (isEdit.value) {
              await axios.put(`/api/maintenance/inspection/${form.id}`, form)
              ElMessage.success('编辑年检记录成功')
            } else {
              await axios.post('/api/maintenance/inspection', form)
              ElMessage.success('添加年检记录成功')
            }
            dialogVisible.value = false
            loadInspectionRecords()
          } catch (error) {
            ElMessage.error(isEdit.value ? '编辑年检记录失败' : '添加年检记录失败')
            console.error('提交表单失败:', error)
          } finally {
            submitLoading.value = false
          }
        } else {
          console.error('表单验证失败:', fields)
        }
      })
    }
    
    // 导出数据
    const exportData = () => {
      ElMessage({
        message: '年检记录导出成功，请在下载中心查看',
        type: 'success',
        duration: 2000
      })
      // 实际项目中应调用导出API
      // window.location.href = '/api/maintenance/inspection/export'
    }
    
    // 获取年检结果类型
    const getResultType = (result) => {
      const types = {
        '通过': 'success',
        '不通过': 'danger',
        '限期整改': 'warning'
      }
      return types[result] || 'info'
    }
    
    return {
      searchQuery,
      inspectionRecords,
      currentPage,
      pageSize,
      DEFAULT_PAGE_SIZES,
      total,
      dialogVisible,
      isEdit,
      form,
      formRef,
      rules,
      vehicles,
      loading,
      submitLoading,
      loadInspectionRecords,
      debounceSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      openAddDialog,
      handleEdit,
      handleDelete,
      submitForm,
      exportData,
      getResultType
    }
  }
}
</script>

<style scoped>
.el-table :deep(.el-table__header) th {
  font-weight: 600;
}

.el-card {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border-radius: 8px;
}

.card-with-hover:hover {
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
  transform: translateY(-3px);
}

.status-tag {
  min-width: 70px;
  text-align: center;
  font-weight: 500;
  border-radius: 4px;
  transition: all 0.3s;
}

.btn-with-icon {
  display: flex;
  align-items: center;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.btn-with-icon:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.custom-table {
  border-radius: 8px;
  overflow: hidden;
}

.custom-pagination {
  margin-top: 16px;
}

.custom-dialog :deep(.el-dialog__header) {
  border-bottom: 1px solid #eee;
  padding: 16px 20px;
}

.custom-dialog :deep(.el-dialog__footer) {
  border-top: 1px solid #eee;
  padding: 16px 20px;
}

.search-input {
  transition: all 0.3s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

.search-input:focus {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

/* 编辑和删除按钮样式 */
.edit-btn, .delete-btn {
  transition: all 0.3s;
}

.edit-btn:hover, .delete-btn:hover {
  transform: translateY(-2px);
}

.edit-btn:hover {
  background-color: var(--el-color-primary-light-3);
}

.delete-btn:hover {
  background-color: var(--el-color-danger-light-3);
}

/* 表格行样式 */
:deep(.el-table__row) {
  transition: all 0.3s;
}

:deep(.el-table__row:hover) {
  background-color: var(--el-color-primary-light-9) !important;
  transform: translateY(-2px);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

/* 修复暗黑模式下的表格样式 */
:deep(.dark-theme .el-table) {
  --el-table-border-color: var(--border-color);
  --el-table-header-bg-color: var(--bg-color);
}

/* 暗黑模式下的卡片悬浮效果 */
:deep(.dark-theme .card-with-hover:hover) {
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.3);
}
</style> 